//
//  APPManager.swift
//  ADKit
//
//  Created by Adoma on 2020/10/22.
//

import SwiftyJSON

/// by ADKit
public struct APPManager {
    
    public struct Env {
        
        public static let release = Env(type: .release)
        public static let prepare = Env(type: .prepare)
        public static let test = Env(type: .test)
        public static let dev = Env(type: .dev)
        public static let local = Env(type: .local)

        public enum EnvType: String {
            case release = "生产环境"
            case prepare = "灰度环境"
            case test = "测试环境"
            case dev = "开发环境"
            case local = "本地环境"
        }
        
        public let type: EnvType
        public let name: String
        public let isDefault: Bool

        public init(type: EnvType = .release, name: String = "", isDefault: Bool = false) {
            self.type = type
            self.name = name
            self.isDefault = isDefault
        }
        
        var identifer: String {
            return type.rawValue + (name.isEmpty ? "" : "-\(name)")
        }
    }
    
    public static var shared = APPManager()
    public private(set) var env: Env = .release

    var envs: [Env] = []
    var testUrl: String? = nil
    var isTest = false
    
    public struct Config {
        
        let isTest: Bool
        let defaultEnv: Env
        let envs: [Env]
        let testUrl: String?
        
        public init(isTest: Bool = false, defaultEnv: Env = .release, envs: [Env] = [], testUrl: String? = nil) {
            self.isTest = isTest
            self.defaultEnv = defaultEnv
            self.envs = envs
            self.testUrl = testUrl
        }
    }
    
    public mutating func start(_ config: Config = Config()) {
        
        self.isTest = config.isTest
        self.envs = config.envs
        self.testUrl = config.testUrl
        
        if isTest,
           let identifer = DataManager.storage.string(for: .environment),
           let current = envs.first(where: { $0.identifer == identifer }) {
            self.env = current
        } else {
            self.env = envs.first(where: { $0.isDefault }) ?? config.defaultEnv
        }
    }
    
    mutating func change(env: Env) {
        self.env = env
        DataManager.storage.set(string: env.identifer, for: .environment)
        NotificationCenter.default.post(name: ADKit.NotificationName.changeAppEnv, object: nil)
    }
}

fileprivate extension DataStorageType.Key {
    static let environment = "APPManager_Environment"
}
